/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hilton.tigershark.titlebar;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.PaintDrawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.hilton.net.UrlUtils;
import com.hilton.tigershark.BrowserActivity;
import com.hilton.tigershark.R;
import com.hilton.tigershark.Tab;
import com.hilton.tigershark.TabControl;
import com.hilton.tigershark.titlebar.UrlInputView.StateListener;
import com.hilton.tigershark.titlebar.UrlInputView.UrlInputListener;

/**
 * This class represents a title bar for a particular "tab" or "window" in the
 * browser.
 */
public class TitleBar extends LinearLayout {
    private static final String TAG = "TitleBar";

    private UrlInputView mUrlInput;
    private ImageView       mOpenBookmarks;
    private ProgressBar     mHorizontalProgress;
    private ImageView       mFavicon;
    private ImageView       mLockIcon;
    private ImageView       mStopButton;
    private boolean         mLoadingWebpage;
    private BrowserActivity mBrowserActivity;
    private Drawable        mGenericFavicon;
    private boolean mShowLock = false;
    private String mUrl;
    private String mTitle;

    public TitleBar(Context activity) {
        this(activity, null);
    }
    
    public TitleBar(Context activity, AttributeSet attrs) {
        super(activity, attrs);
        LayoutInflater factory = LayoutInflater.from(activity);
        factory.inflate(R.layout.title_bar, this);
        mBrowserActivity = (BrowserActivity) activity;

        mHorizontalProgress = (ProgressBar) findViewById(R.id.progress_horizontal);
        mGenericFavicon = activity.getResources().getDrawable(R.drawable.app_web_browser_sm);
        mLockIcon = (ImageView) findViewById(R.id.lock);
        mOpenBookmarks = (ImageView) findViewById(R.id.open_bookmarks);
        mFavicon = (ImageView) findViewById(R.id.favicon);
        mStopButton = (ImageView) findViewById(R.id.stop);
        mUrlInput = (UrlInputView) findViewById(R.id.title);
        mUrlInput.setContainer(this);
        mUrlInput.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    final String url = mBrowserActivity.getWebpageUrl();
                    if (!TextUtils.isEmpty(url)) {
                        mUrlInput.setText(url);
                    }
                    mUrlInput.selectAll();
                } else {
                    final String title = mBrowserActivity.getWebpageTitle();
                    if (!TextUtils.isEmpty(title)) {
                        mUrlInput.setText(title);
                    }
                }
            }
        });
        mUrlInput.setStateListener(new StateListener() {
            @Override
            public void onStateChanged(int state) {
                switch (state) {
                case STATE_NORMAL:
                    mFavicon.setVisibility(View.VISIBLE);
                    if (mLoadingWebpage) {
                        mStopButton.setVisibility(View.VISIBLE);
                    } else {
                        mOpenBookmarks.setVisibility(View.VISIBLE);
                    }
                    if (mShowLock) {
                        mLockIcon.setVisibility(View.VISIBLE);
                    }
                    break;
                case STATE_HIGHLIGHTED:
                    mFavicon.setVisibility(View.GONE);
                    break;
                case STATE_EDITED:
                    mFavicon.setVisibility(View.GONE);
                    if (mLoadingWebpage) {
                        mStopButton.setVisibility(View.GONE);
                    } else {
                        mOpenBookmarks.setVisibility(View.GONE);
                    }
                    mLockIcon.setVisibility(View.GONE);
                    break;
                default:
                    break;
                }
            }
        });
        mUrlInput.setUrlInputListener(new UrlInputListener() {
            @Override
            public  void onDismiss() {
                Log.e(TAG, "what the fuck on dismiss");
            }

            @Override
            public void onAction(String text, String extra, String source) {
                Log.e(TAG, "on action text " + text + ", extra " + extra + ", source " + source);
                mBrowserActivity.focusOnWebpage();
                final String url = UrlUtils.smartUrlFilter(text, false);
                final Tab t = mBrowserActivity.getActiveTab();
                if (!TextUtils.isEmpty(url) && t != null) {
                    mBrowserActivity.loadUrl(url);
                    setDisplayTitle(text);
                    return;
                }
                // TODO: implement search here
            }

            @Override
            public void onCopySuggestion(String text) {
                Log.e(TAG, "on copy suggestion " + text);
            }
        });

        mStopButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mLoadingWebpage) {
                    mBrowserActivity.stopLoading();
                }
            }
        });
        mOpenBookmarks.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mBrowserActivity.bookmarksOrHistoryPicker();
            }
        });
    }

    // TODO: remove it from titlebar
    @Override
    public void createContextMenu(ContextMenu menu) {
        MenuInflater inflater = mBrowserActivity.getMenuInflater();
        inflater.inflate(R.menu.title_context, menu);
        mBrowserActivity.onCreateContextMenu(menu, this, null);
    }

    @Override
    public boolean dispatchKeyEventPreIme(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            mBrowserActivity.focusOnWebpage();
        }
        return super.dispatchKeyEventPreIme(event);
    }
    
    /* package */ void setFavicon(Bitmap icon) {
        Drawable[] array = new Drawable[3];
        array[0] = new PaintDrawable(Color.BLACK);
        PaintDrawable p = new PaintDrawable(Color.WHITE);
        array[1] = p;
        if (icon == null) {
            array[2] = mGenericFavicon;
        } else {
            array[2] = new BitmapDrawable(icon);
        }
        LayerDrawable d = new LayerDrawable(array);
        d.setLayerInset(1, 1, 1, 1, 1);
        d.setLayerInset(2, 2, 2, 2, 2);
        mFavicon.setImageDrawable(d);
    }

    /* package */ void toggleLockIcon(Drawable d) {
        if (null == d) {
            mLockIcon.setVisibility(View.GONE);
            mShowLock = false;
        } else {
            mLockIcon.setImageDrawable(d);
            mLockIcon.setVisibility(View.VISIBLE);
            mShowLock = true;
        }
    }

    /* package */ void setProgress(int newProgress) {
        if (newProgress >= mHorizontalProgress.getMax()) {
            mHorizontalProgress.setVisibility(View.GONE);
            mStopButton.setVisibility(View.GONE);
            mOpenBookmarks.setVisibility(View.VISIBLE);
            mLoadingWebpage = false;
        } else {
            mHorizontalProgress.setProgress(newProgress);
            if (!mLoadingWebpage && getWindowToken() != null) {
                mHorizontalProgress.setVisibility(View.VISIBLE);
                mStopButton.setVisibility(View.VISIBLE);
                mOpenBookmarks.setVisibility(View.GONE);
                mLoadingWebpage = true;
            }
        }
    }

    /* package */ void setDisplayTitle(String title) {
        if (!mUrlInput.hasFocus()) {
            if (title == null) {
                mUrlInput.setText(R.string.title_bar_loading);
            } else {
                mUrlInput.setText(title);
            }
            mUrlInput.setSelection(0);
        }
    }
}